/*
 * Project: Payment
 * Document: SimpleChain
 * Date: 2020/9/16 3:32 下午
 * Author: wangbz
 *
 * Copyright © 2020 www.ixiachong.com Inc. All rights reserved.
 * 注意：本内容仅限于深圳瞎充集团有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
package com.chain;


public class SimpleChain<C> implements Chain {
    private Chain next;
    private ChainHandler<C> handler;
    private C context;

    SimpleChain(final Chain next, final ChainHandler<C> handler, final C context) {
        this.next = next;
        this.handler = handler;
        this.context = context;
    }

    public static <C> SimpleChainBuilder<C> builder() {
        return new SimpleChain.SimpleChainBuilder<C>();
    }

    public static class SimpleChainBuilder<C> {
        private Chain next;
        private ChainHandler<C> handler;
        private C context;

        SimpleChainBuilder() {
        }

        public SimpleChain.SimpleChainBuilder<C> next(final Chain next) {
            this.next = next;
            return this;
        }

        public SimpleChain.SimpleChainBuilder<C> handler(final ChainHandler<C> handler) {
            this.handler = handler;
            return this;
        }

        public SimpleChain.SimpleChainBuilder<C> context(final C context) {
            this.context = context;
            return this;
        }

        public SimpleChain<C> build() {
            return new SimpleChain<C>(this.next, this.handler, this.context);
        }
    }

    @Override
    public void handle() {
        try {
            handler.handle(next, context);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
